package com.chenyue.cm.decrypt;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author libingxing
 */
@Component
public class ParamEncodeResolver extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        ParamEncode annotation;
//        判断是否是方法
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(ParamEncode.class);
        } else {
            return true;
        }
//        判断方法是否带有加密注解
        if (annotation != null) {
            Object paramObj = request.getAttribute("param");
            if (paramObj != null) {
                //这个param为空，默认返回值"null"
                String attribute = request.getAttribute("param") + "";
//                EncodeUtils utils = new EncodeUtils("f2cb9dcb5c0ae0867a566cc8", "de200d9a22495787749b3a36");
                EncodeUtils utils = EncodeUtils.getInstance();
                String decrypt = null;
                try {
                    decrypt = utils.decrypt(attribute);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                request.setAttribute("param", decrypt);
                return true;
            }
            String param = request.getParameter("data");

            if (StringUtils.isNoneBlank(param)) {

                EncodeUtils utils = EncodeUtils.getInstance();

                String decrypt = null;
                try {
                    decrypt = utils.decrypt(param);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                request.setAttribute("param", decrypt);
            }

        }

        return true;
    }

}
